<?php

namespace app\yperp\logic\yp;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use think\Db;

class YpGoods
{
    private static $instance;
    protected  $token;
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
 
    function token(){
        return YpLogin::getInstance()->login('csmb', 'hcyp1234!');
    }
    protected  function Request($method = 'POST', $url, $body = null)
    {
        $client = new Client([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        $headers = [
            'Content-Type' => 'application/json;charset=UTF-8',
            'token' => $this->token(),
        ];
        // $body = '{"page": 1,"limit": 10,"startTime": "2024-02-17","endTime": "2024-03-19"}';
        $body = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $request = new Request($method, $url, $headers, $body);
        $response = $client->sendAsync($request)->wait();
        $data = $response->getBody()->getContents();
        // dump($data);
        $data = json_decode($data, true);
        return $data;
    }

    public function getGoodsById($id)
    {
        $datas = $this->Request('POST', 'https://yp.changhong.com/platform-frame-web-admin/api/goods/get/id/' . $id);
        return $datas['body'];
    }

    public function getAllGoods()
    {
        $variable =   $this->Request('POST', 'https://yp.changhong.com/platform-frame-web-admin/api/goods/queryPageListByScope', ["page" => 1, "limit" => 150, "goodsStatus" => 2, "ifStockSet" => 2]);
        $records = $variable['body']['records'];
        foreach ($records as  $value) {
            // dump($value['id']);
            $re =   $this->getGoodsById($value['id']);
            $this->saveGoods($re);
        }
    }

    public function saveGoods($params)
    {

        // dump($re);
        //修改限购地区并保存
        $re['salesAreaId'] = "825584705806146458";

        $re =   $this->Request('POST', 'https://yp.changhong.com/platform-frame-web-admin/api/goods/save', $params);
        // dump($re);
    }
}
